import React, {useCallback, useEffect, useState} from "react"
import {Table} from "antd";
import DataPageLayout from "../../components/DataPageLayout";
import {NumberIdAndName} from "../../types/BasicModels";
import {
    getAllCheckInventoryRecordCreatedEmployees,
    QueryCheckInventoryRecordResponse,
    queryCheckInventoryRecords
} from "../../apis/CheckInventoryRecordApi";
import {Pageable} from "../../utils/Page";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import {observerDashboardPageWrapper} from "./ObserverDashboardPageWrapper";
import {createUseStyles} from "react-jss";
import {useGlobalStyle} from "../../global.style";
import {useNavigate} from "react-router-dom";
import {YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";

const useStyle = createUseStyles({
    table: {
        "tbody": {
            "tr:hover": {
                cursor: "pointer"
            }
        }
    }
});

export interface pageProps {

}

export interface CheckInventoryRecordFormData {
    marketId: number
}


const CheckInventoryRecordPage: React.FC<pageProps> = (props) => {
    const styles = useStyle()
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryCheckInventoryRecordResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    const [employeeIds, setEmployeeIds] = useState<number[]>([])


    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const [submitted, setSubmitted] = useState<boolean>()
    const query = useCallback(() => {
        setLoading(true)
        queryCheckInventoryRecords({
            employeeIds,
            startDate: startDate ? LocalDate.parse(startDate).toString() : undefined,
            endDate: endDate ? LocalDate.parse(endDate).toString() : undefined,
            submitted,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), employeeIds, startDate, endDate, submitted])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllCheckInventoryRecordCreatedEmployees().then(response => response.data).then(setCreatedByEmployees)
    }, []);


    let navigate = useNavigate();

    let globalStyle = useGlobalStyle();
    return <>
        <DataPageLayout>
            <Table<QueryCheckInventoryRecordResponse> className={`${styles.table} ${globalStyle.rowClickableTable}`} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/checkInventoryRecords/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setEmployeeIds(filters["createdBy.name"] as number[])
                let filter = filters["submittedDateTime"] as unknown as boolean[];
                setSubmitted(filter ? filter[0] : undefined)
            }}>
                <Table.Column dataIndex={"name"} title={"名称"}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                <Table.Column dataIndex={"createdDateTime"} title={"创建时间"}
                              {...useTableFilterDateRangeColumnProps<QueryCheckInventoryRecordResponse>("createdDateTime", {
                                  handleSearch: value => {
                                      setStartDate(value ? value[0].format() : undefined)
                                      setEndDate(value ? value[1].format() : undefined)
                                  }
                              })}
                              render={(value) => value.format(YEAR_MONTH_DAY_FORMATER)}/>
                <Table.Column<QueryCheckInventoryRecordResponse> dataIndex={"submittedDateTime"}
                                                                 filteredValue={submitted ? [submitted] : []}
                                                                 title={"提交时间"}
                                                                 key={"status"}
                                                                 filterMultiple={false}
                                                                 filters={[{
                                                                     text: "已提交",
                                                                     value: true
                                                                 }, {
                                                                     text: "待提交",
                                                                     value: false
                                                                 }]} render={(value) => value?value.format(YEAR_MONTH_DAY_FORMATER):""}/>
                <Table.Column dataIndex={["createdBy", "name"]} title={"创建人"}
                              filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
            </Table>
        </DataPageLayout>
    </>
}
export default observerDashboardPageWrapper(CheckInventoryRecordPage, "checkInventoryRecords", "盘点")
